<template>
	<view>
		<view class="loginForm" v-show="showLoginForm<5">
			<image class="login-icon" src="/static/logo.png" @click="showLoginForm++" />
			<button class="wxlogin-button" @click="wxLogin">
				微信授权
			</button>
		</view>
		<view class="loginForm" v-show="showLoginForm>=5">
			<input class="login-input" v-model="loginForm.username" placeholder=" 账户" />
			<input class="login-input" password v-model="loginForm.password" placeholder=" 密码" />
			<button class="login-button" @click="doLogin">
				密码登录
			</button>
		</view>
	</view>
</template>

<script>
	import {
		getToken
	} from "../../common/utils/auth";
	import {
		getUserInfo
	} from "../../common/api/oauthServer/user";

	export default {
		data() {
			return {
				forumUrl: '/pages/forum/index',
				showLoginForm: 0,
				loginForm: {
					username: 'test_user',
					password: '123456',
					grantType: 'password',
				}
			}
		},
		onLoad() {
			if (getToken()) {
				getUserInfo().then(res => {
						let userInfo = res;
						userInfo.access_token = token
						this.$store.commit('SET_USERINFO', userInfo)
				})
				uni.switchTab({
					url: this.forumUrl
				})
			}
		},
		methods: {
			doLogin() {
				if (getToken()) {
					uni.switchTab({
						url: this.forumUrl
					})
				} else {
					this.$store.dispatch("login", this.loginForm).then(() => {
						this.$websocket.connectSocketInit()
						uni.navigateBack({
							fail: () => {
								uni.switchTab({
									url: this.forumUrl
								})
							}
						})
					}).catch(err => {
						console.log(err)
					})
				}
			},
			wxLogin() {
				uni.login({
					provider: 'weixin',
					success: async (loginRes) => {
						console.log(loginRes)
						if (loginRes.errMsg === 'login:ok') {
							// 执行登录校验逻辑
							this.$store.dispatch("wechartLogin", loginRes.code).then(() => {
								this.$websocket.connectSocketInit()
								uni.navigateBack({
									fail: () => {
										uni.switchTab({
											url: this.forumUrl
										})
									}
								})
							}).catch(err => {
								console.log(err)
							})
						}
					},
					fail: (loginRes) => {
						uni.showToast({
							title: '微信授权失败',
							icon: 'error',
							mask: true,
						})
					}
				})
			},
		}
	}
</script>

<style lang="scss">
	.loginForm {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.login-icon {
		margin-top: 50rpx;
		width: 250rpx;
		height: 250rpx;
	}

	.login-input {
		border: 1rpx solid #d2d2d2;
		border-radius: 10rpx;
		width: 70%;
		height: 80rpx;
		margin-top: 50rpx;
	}

	.login-navigators {
		display: flex;
		flex-direction: row;
	}

	.login-navigators navigator {
		margin-left: 10rpx;
		margin-right: 10rpx;
	}

	.login-button {
		width: 70%;
		margin-top: 50rpx;
	}

	.wxlogin-button {
		width: 70%;
		margin-top: 50rpx;
		margin-bottom: 50rpx;
		background-color: steelblue
	}
</style>
